package com.activitycode.activity.square;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.prefs.Preferences;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.activitycode.city.City;
import com.activitycode.city.CityDbHelp;
import com.activitycode.city.MyLetterListView;
import com.activitycode.city.MyLetterListView.OnTouchingLetterChangedListener;
import com.activitycode.city.PinyinUtils;
import com.activitycode.datamodel.RegionInfo;
import com.activitycode.util.LogUtil;
import com.activitycode.util.SharedPreferrenceManager;
import com.duostec.zhuyue.pets.R;
import com.j256.ormlite.dao.Dao;

public class CityActivity extends Activity {
	private String Tag = "CityActivity";
	private BaseAdapter adapter;
	private ListView personList;
	private TextView overlay;// 对话框首字母textview
	private TextView  titleText;
	private Button btnButton;
	private MyLetterListView letterListView; // A-Z listview
	private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
	private String[] sections;// 存放存在的汉语拼音首字母
	private String[] citys = null;// 存放城市名
	private Handler handler;
	private OverlayThread overlayThread; // 显示首字母对话框
	private ArrayList<City> allCity_lists; // 所有城市列表
	private ArrayList<City> city_lists;// 城市列表
	ListAdapter.TopViewHolder topViewHolder;
	private String lngCityName = "正在定位所在位置..";

	private ImageButton back;
	ArrayAdapter<String> av;

	private Dao<RegionInfo, String> regionInfoDao;
	private CityDbHelp dbHelp;

	List<RegionInfo> provinceList;
	List<RegionInfo> cityList;
	List<RegionInfo> aCityList = new ArrayList<RegionInfo>();
	String[] cityArray;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_choose);
		init();
	}

	private List<RegionInfo> initCity(String parentId) {
		List<RegionInfo> cityListItem = new ArrayList<RegionInfo>();
		try {

			cityListItem = regionInfoDao.queryBuilder().where()
					.eq("parent_id", parentId).query();
			//

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return cityListItem;

	}

	private void initProvince() {

		try {
			provinceList = regionInfoDao.queryBuilder().where()
					.eq("parent_id", "0").query();

			LogUtil.e("provinceList.size:  " + provinceList.size());
			for (int i = 0; i < provinceList.size(); i++) {
				Log.e("Task",
						"name=" + "" + provinceList.get(i).region_id + "*"
								+ provinceList.get(i).parent_id + "*"
								+ provinceList.get(i).region_name + "*"
								+ provinceList.get(i).region_type + "*"
								+ provinceList.get(i).agency_id);

			}
			aCityList.add(provinceList.get(0));
			aCityList.add(provinceList.get(23));
			aCityList.add(provinceList.get(25));
			aCityList.add(provinceList.get(30));
			aCityList.add(provinceList.get(31));
			aCityList.add(provinceList.get(32));
			aCityList.add(provinceList.get(33));
			LogUtil.e("provinceList.size:  " + provinceList.size());
			provinceList.remove(0);
			provinceList.remove(22);
			provinceList.remove(23);
			provinceList.remove(27);
			provinceList.remove(27);
			provinceList.remove(27);
			provinceList.remove(27);
			LogUtil.e("provinceList.size:  " + provinceList.size());

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private ArrayList<City> getCityList() {

		ArrayList<City> cityAList = new ArrayList<City>();
		List<RegionInfo> cityArrayItem1 = new ArrayList<RegionInfo>();

		List<RegionInfo> cityArrayItemT = new ArrayList<RegionInfo>();
		initProvince();
		if (provinceList != null && provinceList.size() > 0) {
			for (int i = 0; i < provinceList.size(); i++) {
				cityArrayItem1 = initCity(provinceList.get(i).region_id);
				cityArrayItemT.addAll(cityArrayItem1);
			}
		}
		cityArrayItemT.addAll(aCityList);

		if (cityArrayItemT.size() > 0) {
			for (int i = 0; i < cityArrayItemT.size(); i++) {
				String pinyi = PinyinUtils
						.getFirstSpell(cityArrayItemT.get(i).region_name);
				City city = new City(cityArrayItemT.get(i).region_name, pinyi,
						cityArrayItemT.get(i).region_id);
				cityAList.add(city);

			}
		}
		Collections.sort(cityAList, comparator);
		return cityAList;

	}

	private void init() {

		dbHelp = CityDbHelp.getHelper(getApplicationContext());
		try {
			regionInfoDao = dbHelp.getRegionInfoDao();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		back = (ImageButton) findViewById(R.id.title_find_info_back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}

		});
		titleText = (TextView) findViewById(R.id.title_find_info_name);
		titleText.setText("选择城市");
		btnButton = (Button) findViewById(R.id.title_search_submit);
		btnButton.setVisibility(View.GONE);
		
		personList = (ListView) findViewById(R.id.list_view);
		allCity_lists = new ArrayList<City>();
		letterListView = (MyLetterListView) findViewById(R.id.MyLetterListView01);
		letterListView
				.setOnTouchingLetterChangedListener(new LetterListViewListener());
		// HomeActivity.setLocateIn(new GetCityName());
		alphaIndexer = new HashMap<String, Integer>();
		handler = new Handler();
		overlayThread = new OverlayThread();
		personList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Log.i(Tag, "" + arg2);
				// Toast.makeText(getApplicationContext(),
				// allCity_lists.get(arg2).name, Toast.LENGTH_SHORT).show();

				SharedPreferences.Editor editor = getSharedPreferences(
						"chooseCity", 0).edit();
				editor.clear();
				editor.putString("city", allCity_lists.get(arg2).id);
				LogUtil.e(" allCity_lists.get(arg2).id   "
						+ allCity_lists.get(arg2).id);
				editor.commit();

				Intent intent = new Intent();
				intent.putExtra("cityString", allCity_lists.get(arg2).name);
				setResult(RESULT_OK, intent);
				finish();

			}
		});
		personList.setAdapter(adapter);
		initOverlay();
		hotCityInit();
		setAdapter(allCity_lists);
	}

	/**
	 * 热门城市
	 */
	public void hotCityInit() {
		City city ;
		
		city = new City("大连", "", "245");
		allCity_lists.add(city);
		city = new City("上海", "", "025");
		allCity_lists.add(city);
		city = new City("北京", "", "02");
		allCity_lists.add(city);
		city = new City("广州", "", "076");
		allCity_lists.add(city);
		city = new City("深圳", "", "077");
		allCity_lists.add(city);
		city = new City("武汉", "", "0180");
		allCity_lists.add(city);
		city = new City("天津", "", "027");
		allCity_lists.add(city);
		city = new City("西安", "", "0311");
		allCity_lists.add(city);
		city = new City("南京", "", "220");
		allCity_lists.add(city);
		city = new City("杭州", "", "0383");
		allCity_lists.add(city);
		city = new City("成都", "", "0322");
		allCity_lists.add(city);

		city_lists = getCityList();
		allCity_lists.addAll(city_lists);
	}

	/**
	 * a-z排序
	 */
	Comparator comparator = new Comparator<City>() {
		@Override
		public int compare(City lhs, City rhs) {
			String a = lhs.getPinyi().substring(0, 1);
			String b = rhs.getPinyi().substring(0, 1);
			int flag = a.compareTo(b);
			if (flag == 0) {
				return a.compareTo(b);
			} else {
				return flag;
			}

		}
	};

	private void setAdapter(List<City> list) {
		adapter = new ListAdapter(this, list);
		personList.setAdapter(adapter);
	}

	public class ListAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private List<City> list;
		final int VIEW_TYPE = 3;
		private Context mContext;

		public ListAdapter(Context context, List<City> list) {
			this.mContext = context;
			this.inflater = LayoutInflater.from(context);
			this.list = list;
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[list.size()];
			citys = new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				// 当前汉语拼音首字母
				String currentStr = getAlpha(list.get(i).getPinyi());
				// 上一个汉语拼音首字母，如果不存在为“ ”
				String previewStr = (i - 1) >= 0 ? getAlpha(list.get(i - 1)
						.getPinyi()) : " ";
				if (!previewStr.equals(currentStr)) {
					String name = getAlpha(list.get(i).getPinyi());
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
				citys[i] = list.get(i).name;
			}
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getItemViewType(int position) {
			// TODO Auto-generated method stub
			int type = 0;
			if (position == 0) {
				type = 2;
			} else if (position == 1) {
				type = 1;
			}
			return type;
		}

		@Override
		public int getViewTypeCount() {// 这里需要返回需要集中布局类型，总大小为类型的种数的下标
			return VIEW_TYPE;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			
			
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.city_list_item, null);
				holder = new ViewHolder();
				holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
//			if (position >= 0) {
				holder.name.setText(list.get(position).getName());
				String currentStr = getAlpha(list.get(position).getPinyi());
				String previewStr = (position - 1) >= 0 ? getAlpha(list.get(
						position - 1).getPinyi()) : " ";
				if (!previewStr.equals(currentStr)) {
					holder.alpha.setVisibility(View.VISIBLE);
					if (currentStr.equals("#")) {
						currentStr = "热门城市";
					}
					holder.alpha.setText(currentStr);
				} else {
					holder.alpha.setVisibility(View.GONE);
				}
//			}
			
			return convertView;
		}

		private class ViewHolder {
			TextView alpha; // 首字母标题
			TextView name; // 城市名字
		}

		private class TopViewHolder {
			TextView alpha; // 首字母标题
			TextView name; // 城市名字
		}

		private class ShViewHolder {
			AutoCompleteTextView editText;

		}
	}

	// 初始化汉语拼音首字母弹出提示框
	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.city_overlay, null);
		overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		WindowManager windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s);
				personList.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.VISIBLE);
				handler.removeCallbacks(overlayThread);
				// 延迟一秒后执行，让overlay为不可见
				handler.postDelayed(overlayThread, 1500);
			}
		}

	}

	// 设置overlay不可见
	private class OverlayThread implements Runnable {
		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

	// 获得汉语拼音首字母
	private String getAlpha(String str) {

		if (str.equals("-")) {
			return "&";
		}
		if (str == null) {
			return "#";
		}
		if (str.trim().length() == 0) {
			return "#";
		}
		char c = str.trim().substring(0, 1).charAt(0);
		// 正则表达式，判断首字母是否是英文字母
		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		if (pattern.matcher(c + "").matches()) {
			return (c + "").toUpperCase();
		} else {
			return "#";
		}
	}

}